#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
衰减器补偿计算器
专门负责根据校准数据计算衰减补偿的类
"""

import logging
from typing import Dict, Optional, Tuple
from calibration_data_reader import CalibrationDataReader


class AttenuatorCompensator:
    """衰减器补偿计算器
    
    职责：
    1. 根据校准数据计算设备能力范围
    2. 验证和调整用户输入的目标衰减值
    3. 计算实际需要设置给衰减器的值
    4. 提供详细的补偿信息和预期结果
    """
    
    def __init__(self, calibration_reader: Optional[CalibrationDataReader] = None):
        """初始化补偿计算器
        
        Args:
            calibration_reader: 校准数据读取器实例
        """
        self.calibration_reader = calibration_reader
        self.min_setting = 0.0      # 衰减器最小设置值
        self.max_setting = 95.0     # 衰减器最大设置值
        
    def set_calibration_reader(self, calibration_reader: CalibrationDataReader):
        """设置校准数据读取器
        
        Args:
            calibration_reader: 校准数据读取器实例
        """
        self.calibration_reader = calibration_reader

    def get_required_setting(self, frequency: float, target_attenuation: float):
        """获取完整的补偿信息（包括验证和计算）

        Args:
            frequency: 频率 (MHz)
            target_attenuation: 目标衰减值 (dB)

        Returns:
            Dict: 完整的补偿信息
        """
        close_frequency = self.calibration_reader.get_frequency_with_interpolation(frequency)
        real_attenuation = self.calibration_reader.get_attenuation_with_interpolation(target_attenuation,
                                                                                      close_frequency)
        if real_attenuation < 0:
            logging.warning(f"目标衰减值 {target_attenuation:.3f}dB 在频率 {frequency:.3f}MHz 下无法实现")
            real_attenuation = 0
        return real_attenuation

    def get_zero_attenuation(self, frequency: float):
        close_frequency = self.calibration_reader.get_frequency_with_interpolation(frequency)
        return self.calibration_reader.get_zero_attenuation(close_frequency)

